package com.hankol.newretail

import android.annotation.SuppressLint
import android.app.AlertDialog
import android.os.Bundle
import android.os.CountDownTimer
import android.text.Editable
import android.text.TextWatcher
import android.view.MotionEvent
import android.view.View
import android.widget.RelativeLayout
import android.widget.TextView
import androidx.lifecycle.Observer
import com.alibaba.android.arouter.facade.annotation.Route
import com.baselibrary.Constants
import com.baselibrary.MessageBus
import com.baselibrary.bean.MediaInfo
import com.baselibrary.extension.checkNotNull
import com.baselibrary.extension.checkValue
import com.baselibrary.extension.toast
import com.baselibrary.manager.SensorsDataManager
import com.baselibrary.router.ActivityRouter
import com.baselibrary.utils.*
import com.baselibrary.view.MyCircleProgress
import com.baselibrary.activity.BaseActivity
import com.baselibrary.view.SpacesVerticalDec
import com.hankol.newretail.adapter.EvaluationUploadImageVideoAdapter
import com.hankol.newretail.arouter.NewRetailHelp
import com.hankol.newretail.bean.AfterSalesApplyCommitBean
import com.hankol.newretail.bean.MallOrderSkuDtoBean
import com.hankol.newretail.databinding.ActivityAfterSalesApplyBinding
import com.hankol.newretail.viewmodel.AfterSalesViewModel
import com.media.publish.bean.MultiImageResp
import com.media.publish.utils.UploadMediaUtils
import com.media.revision.RevisionMediaActivity
import com.media.utils.WineryAboutUtils
import com.xinlan.imageeditlibrary.EditImgMainActivity
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

/**
 * @description 售后申请
 * @author 关忆北、
 * @time 2022/8/10 5:04 下午
 */
@Route(path = ActivityRouter.NEW_RETAIL.AFTER_SALES_APPLY)
class AfterSalesApplyActivity : BaseActivity(), View.OnClickListener, AfterSalesViewModel.OnRefundReasonCallBack, EvaluationUploadImageVideoAdapter.OnItemClickListener {
    private var reApplyDes: String = ""
    private var isReApplyStart = false//是否是重新申请的
    private var shopMaxNum = 0
    private var reasonPos: Int = -1
    private lateinit var viewStation: RelativeLayout.LayoutParams
    private var shopDtoInfoBean: MallOrderSkuDtoBean? = null
    private lateinit var viewModel: AfterSalesViewModel
    private lateinit var dataBinding: ActivityAfterSalesApplyBinding
    private val mNewRetailHelp = ActivityRouter.getARouterInterface<NewRetailHelp>(ActivityRouter.NEW_RETAIL.NEW_RETAIL_HELP)

    private var mMediaUrlList = ArrayList<MediaInfo>()

    override fun getLayoutId(): Int {
        return R.layout.activity_after_sales_apply
    }

    companion object {

    }

    override fun init() {
        dataBinding = getDataBinding<ActivityAfterSalesApplyBinding>()
        viewModel = getActivityViewModelProvider(this).get(AfterSalesViewModel::class.java)
        viewStation = dataBinding.viewStation.layoutParams as RelativeLayout.LayoutParams
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this)
        }
        intent.extras?.let {
            shopDtoInfoBean = it.getParcelable(Constants.KEY_APPLY_AFTER_DTO_INFO_BEAN)
            isReApplyStart = it.getBoolean(Constants.KEY_APPLY_AFTER_RESTART, false)
            if (isReApplyStart) {
                reApplyDes = it.getString(Constants.KEY_APPLY_AFTER_RESTART_DES, "")
                reasonPos = it.getInt(Constants.KEY_APPLY_AFTER_RESTART_REASON, -1)
                val imgList = it.getParcelableArrayList<MediaInfo>(Constants.KEY_APPLY_AFTER_RESTART_IMG)
                if (!imgList.isNullOrEmpty()) {
                    mMediaPathList.addAll(imgList)
                }
            }
        }
        initView()
        loadData()
        initObserve()
        initListener()
        SensorsDataManager.instance.refundApplySee()
    }

    private fun initView() {
        // NestedScrollView嵌套EditText，导致EditText滑动冲突
        dataBinding.editApplyRetreatDes.setOnTouchListener { view, motionEvent ->
            if (view.getId() == R.id.edit_apply_retreat_des && CommonUtil.canVerticalScroll(dataBinding.editApplyRetreatDes)) {
                //通知父控件不要干扰
                view.getParent().requestDisallowInterceptTouchEvent(true);
            }
            if (motionEvent.getAction() == MotionEvent.ACTION_UP) {
                view.getParent().requestDisallowInterceptTouchEvent(false);
            }
            false;
        };
    }

    fun initListener() {
        dataBinding.llAfterApplyRetreatReduce.setOnClickListener(this)
        dataBinding.llAfterApplyRetreatPlus.setOnClickListener(this)
        dataBinding.llApplyRetreatReason.setOnClickListener(this)
        dataBinding.tvAfterApplySubmit.setOnClickListener(this)
        dataBinding.ivBack.setOnClickListener(this)
        dataBinding.editApplyRetreatDes.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {

            }

            override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {

            }

            override fun afterTextChanged(p0: Editable?) {
                upSubmit()
                dataBinding.tvApplyRetreatWordsNum.text = "${p0.toString().length}/300"
            }

        })
        KeyBoardUtils.setListener(this@AfterSalesApplyActivity, object : KeyBoardUtils.OnSoftKeyBoardChangeListener {
            override fun keyBoardShow(height: Int) {
                dataBinding.nsAfter.smoothScrollTo(0, 300)
            }

            override fun keyBoardHide(height: Int) {
                dataBinding.nsAfter.smoothScrollTo(0, 0)
            }

        })

    }

    @SuppressLint("SetTextI18n")
    fun loadData() {
        shopDtoInfoBean?.apply {
            GlideUtils.loadImg_101(applicationContext, skuCover, dataBinding.roundAfterApplyCover)
            dataBinding.tvAfterApplyTitle.text = spuName
            dataBinding.tvAfterApplyNorms.text = SpecUtils.getNormsStr(specList)
            shopMaxNum = num
            if (requestNum > 0) {
                num = requestNum
            }

            if (shopMaxNum == 1) {
                dataBinding.ivAfterApplyRetreatReduce.setImageResource(R.drawable.ic_goods_reduce_false)
                dataBinding.ivAfterApplyRetreatPlus.setImageResource(R.drawable.ic_goods_add_false)
            } else {
                if (num >= shopMaxNum) {
                    num = shopMaxNum
                    dataBinding.ivAfterApplyRetreatReduce.setImageResource(R.drawable.ic_goods_reduce_true)
                    dataBinding.ivAfterApplyRetreatPlus.setImageResource(R.drawable.ic_goods_add_false)
                } else {
                    dataBinding.ivAfterApplyRetreatPlus.setImageResource(R.drawable.ic_goods_add_true)
                    if (num > 1) {
                        dataBinding.ivAfterApplyRetreatReduce.setImageResource(R.drawable.ic_goods_reduce_true)
                    }
                }
            }

            upPrice()
        }
        if (isReApplyStart) {
            dataBinding.editApplyRetreatDes.setText(reApplyDes)
            dataBinding.tvApplyRetreatWordsNum.text = "${reApplyDes.length}/300"
            dataBinding.tvApplyRetreatReason.text = viewModel.reasonStrList[reasonPos.minus(1)]
            upSubmit()
        }
        initUploadImgVideo()
    }

    private lateinit var mImageVideoAdapter: EvaluationUploadImageVideoAdapter
    private var mMediaPathList = ArrayList<MediaInfo>()

    private fun initUploadImgVideo() {
        mImageVideoAdapter = EvaluationUploadImageVideoAdapter(this)
        dataBinding.rvImagevideo.addItemDecoration(SpacesRightDec(ScreenUtils.dip2px(this, 0f)))
        dataBinding.rvImagevideo.addItemDecoration(SpacesVerticalDec(ScreenUtils.dip2px(this, 3f)))
        dataBinding.rvImagevideo.adapter = mImageVideoAdapter
        mImageVideoAdapter.setOnClickListener(this)
        if (isReApplyStart) {
            mImageVideoAdapter.setData(mMediaPathList)
            mImageVideoAdapter.notifyDataSetChanged()
        }
    }

    private fun initObserve() {
        viewModel.applyAfterSaleLD.observe(this, Observer {
            dataBinding.tvAfterApplySubmit.isEnabled = true
            if (it != null && it.afterSaleId != 0L) {
                if (isReApplyStart) {
                    //重新申请
                    EventBusUtils.sendNotify(MessageBus.msgId_retail_after_sales_re_apply_success)
                }
                AppManager.getAppManager().finishActivity(AfterSalesDetailsActivity::class.java)
                EventBusUtils.sendNotify(MessageBus.msgId_after_sale_apply_success)
                ToastUtils.showShort(applicationContext, "申请成功")
                val hasMap: HashMap<String, Any> = hashMapOf()
                hasMap[AfterSalesDetailsActivity.AFTER_SALES_ID] = it.afterSaleId
                ARouterUtils.jump(ActivityRouter.NEW_RETAIL.AFTER_SALES_DETAILS, hasMap)
                finish()
            }
        })
    }

    override fun onClick(p0: View) {
        when (p0.id) {
            R.id.iv_back -> {
                finish()
            }
            R.id.ll_after_apply_retreat_reduce -> {
                //减
                shopDtoInfoBean?.apply {
                    if (num == 1) {
                        ToastUtils.showShort(applicationContext, "最少选择1件")
                        return@apply
                    }
                    num -= 1
                    if (num < 1) num = 1//保险起见
                    if (num == 1) {
                        dataBinding.ivAfterApplyRetreatReduce.setImageResource(R.drawable.ic_goods_reduce_false)
                        dataBinding.ivAfterApplyRetreatPlus.setImageResource(R.drawable.ic_goods_add_true)
                    } else if (num > 1) {
                        dataBinding.ivAfterApplyRetreatReduce.setImageResource(R.drawable.ic_goods_reduce_true)
                        if (num < shopMaxNum) {
                            dataBinding.ivAfterApplyRetreatPlus.setImageResource(R.drawable.ic_goods_add_true)
                        }
                    }
                    upPrice()
                }
                //更新价格
            }
            R.id.ll_after_apply_retreat_plus -> {
                //加
                shopDtoInfoBean?.apply {
                    if (num >= shopMaxNum) {
                        ToastUtils.showShort(applicationContext, "超出最大数量")
                        return@apply
                    }
                    num += 1
                    if (num > shopMaxNum) num = shopMaxNum
                    if (num >= shopMaxNum) {
                        dataBinding.ivAfterApplyRetreatReduce.setImageResource(R.drawable.ic_goods_reduce_true)
                        dataBinding.ivAfterApplyRetreatPlus.setImageResource(R.drawable.ic_goods_add_false)
                    } else {
                        dataBinding.ivAfterApplyRetreatPlus.setImageResource(R.drawable.ic_goods_add_true)
                        if (num > 1) {
                            dataBinding.ivAfterApplyRetreatReduce.setImageResource(R.drawable.ic_goods_reduce_true)
                        }
                    }
                    upPrice()
                }
                //更新价格
            }
            R.id.ll_apply_retreat_reason -> {
                //选择原因
                KeyBoardUtils.hideSoftKeyboard(this@AfterSalesApplyActivity)
                viewModel.showRefundReasonView(this@AfterSalesApplyActivity, this)
            }
            R.id.tv_after_apply_submit -> {
                if (DoubleClickHelper.isOnDoubleClick()) return
                if (mMediaPathList.size == 0) {
                    commitHandle(emptyList())
                } else {
                    showLoading()
                    uploadMedia()
                }
            }
        }
    }

    fun commitHandle(urls: List<MediaInfo>) {
        //提交
        val content = dataBinding.editApplyRetreatDes.text.toString()
        if (content.trim().isNotEmpty() && reasonPos != -1) {
            shopDtoInfoBean?.let {
//                dataBinding.tvAfterApplySubmit.isEnabled = false
                SensorsDataManager.instance.refundApply("${it.popiId}", it.shopName, "${it.spuId}", it.spuName.checkValue(), it.cname.checkValue(), SpecUtils.getNormsStr(it.specList), AmountUtil.changeF2YKeepTwo("${it.price}"), dataBinding.tvApplyRetreatReason.text.toString().checkValue(), AmountUtil.changeF2YKeepTwo((it.num * it.price).toString()))
                viewModel.reqApplyAfterSale(GsonUtils.toJson(AfterSalesApplyCommitBean(urls, reasonPos, content, it.num, it.popiId)))
            }
        } else {
            ToastUtils.showShort(applicationContext, "完善售后信息")
        }
    }

    fun upPrice() {
        shopDtoInfoBean?.apply {
            dataBinding.tvAfterApplyRetreatNumber.text = num.toString()
            dataBinding.tvApplyRetreatPrice.text = "¥${AmountUtil.changeF2YKeepTwo((num * price).toString())}"
        }
    }

    /**
     * 选择的原因绘制
     */
    override fun onRefundReason(str: String, reasonPos: Int) {
        this.reasonPos = reasonPos
        dataBinding.tvApplyRetreatReason.text = str
        upSubmit()
    }

    fun upSubmit() {
        if (dataBinding.editApplyRetreatDes.text.toString().trim().isNotEmpty() && reasonPos != -1) {
            dataBinding.tvAfterApplySubmit.setBackgroundResource(R.drawable.shape_rc_23_solid_f54d53)
        } else {
            dataBinding.tvAfterApplySubmit.setBackgroundResource(R.drawable.shape_rc_23_solid_f54d53_a50)
        }
    }

    override fun onItemClick(pos: Int, list: MutableList<MediaInfo>?) {
        //进入大图
        val urlList = mutableListOf<String>()
        for (datum in list as List<MediaInfo>) {
            urlList.add(if (datum.type == 0) datum.coverUrl else datum.videoUrl)
        }
        seeBigImg(urlList, pos, emptyList())
    }

    private fun seeBigImg(coverUrlList: MutableList<String>, position: Int, descList: List<String>) {
        //查看大图
        val bundle = Bundle()
        bundle.putStringArrayList(Constants.KEY_URLS, coverUrlList as ArrayList<String>)
        bundle.putInt(Constants.KEY_INDEX, position)
        bundle.putStringArrayList(Constants.KEY_COMMENT_CONTENT, if (descList.size == 0) ArrayList<String>() else descList as ArrayList<String>)
        bundle.putStringArrayList(Constants.KEY_COMMENT_TITLE, arrayListOf())
        ActivityRouter.startActivity(ActivityRouter.WINE_CELLAR.IMG_VIDEO_DETAIL, bundle)
    }

    override fun onAddItemClick() {
        var isHaveVideo = false
        for (bean in mMediaPathList) {
            if (bean.type == 1) {
                isHaveVideo = true
            }
        }
        WineryAboutUtils.uploadImgVideo(this, !isHaveVideo, mMediaPathList.size, 9)
    }

    override fun onDeleteItemClick(pos: Int, list: MutableList<MediaInfo>?) {
        PopUtils.showOkCancelDialog(this, "确认删除", object : PopUtils.ICallBack {
            override fun clickOk() {
                mMediaPathList.removeAt(pos)
                mImageVideoAdapter.setData(mMediaPathList)
                "删除成功".toast()
                mImageVideoAdapter.notifyDataSetChanged()
            }

            override fun clickCancel() {

            }

        }, false, "确认", "取消")
    }

    private lateinit var countDownTimer: CountDownTimer
    var uploadLoadingDialog: AlertDialog? = null
    fun showLoading() {
        uploadLoadingDialog = PopUtils.uploadLoadingDialog(this, object : PopUtils.ICallback4Progress {
            override fun progressCallback(progress: MyCircleProgress, tvProgress: TextView) {
                countDownTimer = object : CountDownTimer(60000, 3000) {
                    override fun onTick(millisUntilFinished: Long) {
                        val pro = (60000 - millisUntilFinished) / 1000
                        progress.setMax(60)
                        progress.setCurrent(pro.toInt())
                    }

                    override fun onFinish() {}
                }.start()
            }
        })
        if (!uploadLoadingDialog!!.isShowing) {
            uploadLoadingDialog!!.show()
        }
    }

    fun hideLoading() {
        dataBinding.tvAfterApplySubmit.isEnabled = true
        countDownTimer.cancel()
        if (uploadLoadingDialog.checkNotNull()) {
            uploadLoadingDialog!!.dismiss()
        }
    }

    private fun uploadMedia() {
        val imgList4Path = mutableListOf<String>()
        val indexList4Img = mutableListOf<Int>()
        val videoList4Path = mutableListOf<MediaInfo>()
        val indexList4Video = mutableListOf<Int>()
        mMediaPathList.forEachIndexed { index, mediaInfo ->
            if (mediaInfo.type == 0) {//图片
                if (!mediaInfo.coverUrl.startsWith("http")) {
                    imgList4Path.add(mediaInfo.coverUrl)
                    indexList4Img.add(index)
                }
            } else {//视频
                if (!mediaInfo.videoUrl.startsWith("http")) {
                    indexList4Video.add(index)
                    videoList4Path.add(mediaInfo)
                }
            }
        }
        if (videoList4Path.size > 0) {//有视频
            if (videoList4Path[0].videoUrl.startsWith("http")) {//重新申请，没有上传新的视频
                hideLoading()
                commitHandle(mMediaPathList)
            } else {//有新增新的视频，先上传
                UploadMediaUtils.uploadVideo(videoList4Path[0].videoUrl, object : UploadMediaUtils.UploadVideoListener {
                    override fun onProgress(uploadBytes: Long, totalBytes: Long) {
                    }

                    override fun onComplete(videoUrl: String?, videoCoverUrl: String?) {
                        mMediaUrlList.add(MediaInfo(videoCoverUrl.checkValue(), videoUrl.checkValue(), 1))
                        if (imgList4Path.size > 0) {
                            //判断是否有没上传的图片

                            UploadMediaUtils.uploadImages(imgList4Path as java.util.ArrayList<String>?) { questionRespT ->
                                if (questionRespT.checkNotNull()) {
                                    if (questionRespT!!.data.size > 0) {
                                        for (bean in questionRespT.data) {
                                            mMediaUrlList.add(MediaInfo(bean.ok, "", 0))
                                        }
                                    }
                                }
                                indexList4Video.forEachIndexed { index, pathIndex ->
                                    mMediaPathList[pathIndex].videoUrl = mMediaUrlList[index].videoUrl
                                    mMediaPathList[pathIndex].coverUrl = mMediaUrlList[index].coverUrl
                                }
                                indexList4Img.forEachIndexed { index, pathIndex ->
                                    mMediaPathList[pathIndex].coverUrl = mMediaUrlList[pathIndex].coverUrl
                                }
                                hideLoading()
                                commitHandle(mMediaPathList)
                            }
                        } else {
                            mMediaPathList[0].videoUrl = mMediaUrlList[0].videoUrl
                            mMediaPathList[0].coverUrl = mMediaUrlList[0].coverUrl
                            hideLoading()
                            commitHandle(mMediaPathList)
                        }
                    }
                })
            }
        } else {
            //无视频，有图片
            val needUploadImgPathList = mutableListOf<String>()
            for (pathUrl in imgList4Path) {
                if (!pathUrl.startsWith("http")) {
                    needUploadImgPathList.add(pathUrl)
                }
            }
            if (needUploadImgPathList.size > 0) {
                UploadMediaUtils.uploadImages(needUploadImgPathList as java.util.ArrayList<String>?, object : UploadMediaUtils.UploadImageListener {
                    override fun onComplete(questionRespT: MultiImageResp?) {
                        if (questionRespT.checkNotNull()) {
                            if (questionRespT!!.getData().size > 0) {
                                for (bean in questionRespT.getData()) {
                                    mMediaUrlList.add(MediaInfo(bean.ok, "", 0))
                                }
                            }
                        }
                        indexList4Img.forEachIndexed { index, pathIndex ->
                            mMediaPathList[pathIndex].coverUrl = mMediaUrlList[index].coverUrl
                        }
                        hideLoading()
                        commitHandle(mMediaPathList)
                    }
                })
            } else {
                hideLoading()
                commitHandle(mMediaPathList)
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onEvent(messageBus: MessageBus) {
        if (messageBus.codeType == MessageBus.msgId_select_img_video_path_list) {
            AppManager.getAppManager().finishActivity(RevisionMediaActivity::class.java)
            mNewRetailHelp.finishVideoEditActivity()
            AppManager.getAppManager().finishActivity(EditImgMainActivity::class.java)
            if (messageBus.param1 is String) {//视频  mMediaPathList.add(0, WineryCoverBean("", newPath.checkValue(), 1))
                FileUtils.copyVideoFile(messageBus.param1.toString(), object : FileUtils.OnCopyFileListener {
                    override fun onCopyOver(filePath: String?) {
                        mMediaPathList.add(0, MediaInfo("", filePath.checkValue(), 1))
                    }

                    override fun onCopyError() {
                    }

                })
            } else if (messageBus.param1 is List<*>) {//图片
                var list = messageBus.param1 as List<String>
                for (imageItem in list) {
                    mMediaPathList.add(MediaInfo(imageItem, "", 0))
                }
            }
            //选择轮播
            mImageVideoAdapter.setData(mMediaPathList)
            mImageVideoAdapter.notifyDataSetChanged()
        }
    }

    override fun onDestroy() {
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this)
        }
        super.onDestroy()
    }
}